package com.dengqi.mymodule.wxapi;

//import com.umeng.socialize.weixin.view.WXCallbackActivity;

import android.os.Bundle;
import android.widget.Toast;

import com.module.umlib.WXHelper;
import com.module.umlib.utils.ConstantsUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

/**
 * 微信分享、微信登录 回调
 * Created by cheng on 2017/11/16.
 */
public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {

    private static final String TAG = "WXEntryActivity";
    private static final int RETURN_MSG_TYPE_LOGIN = 1;  ///< 登录
    private static final int RETURN_MSG_TYPE_SHARE = 2;  ///< 分享
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        ///< 这句没有写,是不能执行回调的方法的
        api = WXAPIFactory.createWXAPI(this, ConstantsUtils.WX_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        int type = baseResp.getType(); //类型：分享还是登录
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ///< 用户拒绝授权
                Toast.makeText(getApplicationContext(), "拒绝授权", Toast.LENGTH_SHORT);
                finish();
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ///< 用户取消
                String message = "";
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    message = "取消了微信登录";
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    message = "取消了微信分享";
                }
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
                finish();
                break;
            case BaseResp.ErrCode.ERR_OK:
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    ///< 用户换取access_token的code，仅在ErrCode为0时有效
                    String code = ((SendAuth.Resp) baseResp).code;
                    ///< 这里拿到了这个code，去做2次网络请求获取access_token和用户个人信息
                    WXHelper.onWxLoginListener.onComplete(code);
//                    WXFragment.onWxLoginListener.onComplete(code);
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    ///< "微信分享成功"
                    finish();
                }
                break;
        }
    }


}
